const md5 = require("js-md5")
const jwt = require("jsonwebtoken")
const {
  login
} = require("../services/user.services")
const {
  SERCT_KEY
} = require("../app/config")
const {
  USER_NAME_OR_PASS_WORD,
  USER_NAME_OR_PASSWORD_ERROR,
  TOKEN_SHIXIAO,
  IS_AUTHOR,
  IS_NOT_MOMONET
} = require("../contants/error-type")
const {
  isSameUser
} = require("../services/auth.services")
const loginRules = async (req, res, next) => {
  const { name, password } = req.body;

  // if (name == "" || password == "" || !name || !password) {
  //   return next(new Error(USER_NAME_OR_PASS_WORD))
  // }
  const result = await login(req.body);
  req.user = result[0]  // 全局放入一个user

  if (result.length == 0) {
    return next(new Error(USER_NAME_OR_PASSWORD_ERROR))
  }



  // console.log(result[0],password,  "ppp")
  if (result[0].name !== name || md5(password) !== result[0].password) {
    return next(new Error(USER_NAME_OR_PASS_WORD))
  }
  console.log("你好啊")
  next()




}

// 验证用户是否携带了token 中间件
const verifyAuth = async (req, res, next) => {
  console.log("授权中间件~token")
  const authorization = req.headers.authorization;
  // console.log(req,"999")
  const token = authorization && authorization.replace("Bearer ", "");
  
  try {
    const result = jwt.verify(token, SERCT_KEY);
    console.log(result, "hhah");
    req.user = result  // 全局放入一个user
    await  next()
  } catch (err) {
    await next(new Error(TOKEN_SHIXIAO))
  }

}

// 验证用户修改评论时是否是该用户
const verifyPermison = async (req, res, next) => {
  // 查数据库
  const {id} = req.user;
  const result = await isSameUser(id, req.body.moment_id);
  console.log("你好啊")
  console.log(result[0], "lalla");
  console.log("我很好");
  // try {
  //   // result[0].id 
  // } catch {

  // }
  // console.log(req.body.id,id, req.body.moment_id, req.body.content)
  // let index = result[0] && result[0].findIndex(item => item.moment_id == req.body.moment_id);
  // console.log(index, "index")
  if (result[0].length == 0) {
    return await next(new Error(IS_NOT_MOMONET))
  }
  // if (index == -1) {
  //   return await next(new Error(IS_AUTHOR))
  // }else {
    await next()
  // }
  // res.json("测试")

}

module.exports = {
  loginRules,
  verifyAuth,
  verifyPermison
}